<template>
  <div class="checkout-address">
    <!-- 收货地址 -->
    <div class="box-title">收货地址</div>
    <div class="box-body">
      <div class="address">
        <div class="text">
          <div class="none" v-if="!showAddress">您需要先添加收货地址才可以提交订单。</div>
          <ul v-if="showAddress">
            <li><span>收<i>货</i>人：</span>{{showAddress.receiver}}</li>
            <li><span>联系方式：</span>{{showAddress.contact}}</li>
            <li><span>收货地址：</span>{{showAddress.fullLocation}}{{showAddress.address}}</li>
          </ul>
        </div>
        <a href="javascript:;" @click="openAddressEdit(showAddress)">修改地址</a>
        <div class="action">
          <XtxButton @click="openDialog" class="btn">切换地址</XtxButton>
          <XtxButton  @click="openAddressEdit({})" class="btn">添加地址</XtxButton>
        </div>
      </div>
      <!-- 切换收货地址对话框组件 -->
      <XtxDialog title="切换收货地址" v-model:visible="visibleDialog">
        <template #body>
          <div @click="selectedAddress=item" :class="{active:selectedAddress&&selectedAddress.id===item.id}" class="text item" v-for="item in list" :key="item.id">
            <ul style="width:90%">
              <li><span>收  <i>货  </i>人：</span>{{item.receiver}}</li>
              <li><span>联系方式：</span>{{item.contact}}</li>
              <li><span>收货地址：</span>{{item.fullLocation.replace(/ /g,'')}}{{item.address}}</li>
            </ul>
            <i v-if="showAddress.id!==item.id" class="iconfont icon-close-new closeButton" @click="deleteAddress(item.id)"></i>
          </div>
        </template>
        <template #footer>
          <XtxButton type="gary" style="margin-right:20px" @click="visibleDialog=false">取消</XtxButton>
          <XtxButton  @click="confirmAddressFn()" type="primary">确认</XtxButton>
        </template>
      </XtxDialog>
      <!-- 添加/编辑收货地址对话框 -->
      <AddressEdit @on-success="successHander" ref="addressEditCom"></AddressEdit>
    </div>
  </div>
</template>

<script>
import { ref } from '@vue/reactivity'
import AddressEdit from './components/address-edit.vue'
import { DeleteAddress } from '@/api/order'
import Message from '@/components/library/Message'
export default {
  name: 'CheckoutAddress',
  components: { AddressEdit },
  props: {
    // 收货地址列表
    list: {
      type: Array,
      // 默认是一个空数组
      default: () => []
    }
  },
  setup (props, { emit }) {
    // 1.找到默认收货地址
    // 2.如果没有默认地址，则使用第一条地址
    // 3.没有收货地址，提示添加
    // 显示的地址
    const showAddress = ref(null)
    const defaultAddress = props.list.find(item => item.isDefault === 0)
    if (defaultAddress) { // 找到默认收货地址
      showAddress.value = defaultAddress
    } else { // 第一条收货地址
      if (props.list.length) {
        // eslint-disable-next-line vue/no-setup-props-destructure
        showAddress.value = props.list[0]
      }
    }
    // 默认通知父组件（结算组件）一个收货地址id
    emit('change', showAddress.value ? showAddress.value.id : null)
    // 控制提示框显示与隐藏
    const visibleDialog = ref(false)
    // 点击收货地址列表时 记录当前已选中地址对象
    const selectedAddress = ref(null)
    // 打开切换地址的对话框
    const openDialog = () => {
      visibleDialog.value = true
      // 将之前的选中地址置为空
      selectedAddress.value = null
    }
    // 确认收货地址
    const confirmAddressFn = () => {
      // 1.点击确认时，要将点击的地址展示到showAddress
      // 2.将该收货地址的id传给父组件checkout
      showAddress.value = selectedAddress.value
      emit('change', selectedAddress.value ? selectedAddress.value.id : null)
      visibleDialog.value = false
    }

    // 组件实例
    const addressEditCom = ref(null)
    // 打开添加编辑/添加收货地址的组件
    const openAddressEdit = (address) => {
      // console.log(address)
      // 调用组件实例的方法
      // 添加时传入一个空对象、修改时传入当前收货地址
      addressEditCom.value.open(address)
    }
    //
    const successHander = (formData) => {
      showAddress.value = formData
      // 如果是添加，就往list中追加一条数据
      // 当修改formData时，数组中的数据也会更新 因为是同一个引用地址
      // 当打开对话框 需要清空之前的输入数据 克隆formData数据
      // 根据formData中的id根据当前地址列表中查找，有就是修改否则是添加
      const address = props.list.find(item => item.id === formData.id)
      if (address) {
        // 修改
        for (const key in address) {
          address[key] = formData[key]
        }
      } else {
        // 新增
        const jsonStr = JSON.stringify(formData)
        // eslint-disable-next-line vue/no-mutating-props
        props.list.unshift(JSON.parse(jsonStr))
      }
    }
    // 删除收货地址
    const deleteAddress = (id) => {
      console.log(props.list)
      DeleteAddress(id).then(() => {
        Message({ type: 'success', text: '删除成功' })
        // eslint-disable-next-line vue/no-mutating-props
        props.list.splice(props.list.findIndex(item => item.id === id), 1)
      })
    }
    return {
      addressEditCom,
      showAddress,
      visibleDialog,
      selectedAddress,
      confirmAddressFn,
      openDialog,
      openAddressEdit,
      successHander,
      deleteAddress
    }
  }
}
</script>

<style lang="less" scoped>
.checkout-address{
  .box-title{
      padding: 10px;
      font-size: 16px;
      font-weight: normal;
      line-height: 70px;
      border-bottom: 1px solid #f5f5f5;
    }
    .box-body{
      .address{
        display: flex;
        align-items: center;
        border: 1px solid #f5f5f5;
        .text{
          padding: 20px;
          display: flex;
          flex:1;
          .none{
            font-size: 16px;
            line-height: 90px;
            color:#999;
            text-align: center;
            width: 100%;
          }
          >ul{
            flex:1;
            padding: 20px;
            li{
              margin: 6px 0;
              span{
                font-size: 15px;
                color: #999;
                >i{
                  width: 1.5em;
                  text-align: center;
                  display: inline-block;
                }
              }
            }
          }

        }
        a{
          color: @xtxColor;
          text-align: center;
          width: 160px;
          height: 90px;
          line-height: 90px;
          border-right: 1px solid #f5f5f5;
        }
        .action{
          width: 420px;
          text-align: center;
          .btn{
            width: 140px;
            height: 46px;
            line-height: 44px;
            font-size: 14px;
            &:first-child{
              margin-right: 10px;
            }
            &:hover{
              color: @xtxColor;
              border-color: @xtxColor;
            }
          }
        }
      }
    }
}
.text{
  //display: flex;
  position: relative;
  span{
    color:#999;
  }
  >ul{
    line-height: 30px;
    font-size: 14px;
  }
  .closeButton{
    position: absolute;
    right: 20px;
    top:50%;
    transform: translate(0,-50%);
    width: 30px;
    height: 30px;
    text-align: center;
    line-height: 30px;
    &:hover{
      color: red;
    }
  }
}
.item{
  border: 0.5px solid #f5f5f5;
  padding: 10px;
  margin:10px 0px;
  position: relative;
  &.active,&:hover{
    background-color: lighten(@xtxColor,50%);
    border: 0.5px solid @xtxColor;
    cursor: pointer;
  }
}
</style>
